package com.punai.config.sqlitedao.impl;

import cn.hutool.core.util.StrUtil;
import com.punai.common.exception.ServiceException;
import com.punai.common.utils.sqlite.SqliteUtil;
import com.punai.config.sqlitedao.TemplateLinkItemRepository;
import com.punai.config.sqlitedomain.TemplateLinkItem;
import com.punai.config.sqlitesetting.SqliteSystemTemplConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class TemplateLinkItemRepositoryImpl implements TemplateLinkItemRepository {
    private static SqliteUtil sqliteUtil;
    private static final Logger log = LoggerFactory.getLogger(TemplateLinkItemRepository.class);

    @Autowired
    private SqliteSystemTemplConnection sqliteSystemTemplConnection;

    private void initConnection() {
        sqliteUtil = sqliteSystemTemplConnection.initConnection();
    }


    @Override
    public void save(String templateId, List<String> itemIds)  {
        initConnection();
        String Sql = "insert into "
                + "tab_config_link_template_item" +
                "(TEMPLATE_ID ," +
                "ELEMENT_ID) "
                + "values(?,?) ";
        for (String itemId : itemIds) {
            TemplateLinkItem one = this.findOne(templateId, itemId);
            if(one==null|| StrUtil.isBlank(one.getTemplateId())){
                Object[] args = new Object[]{
                        templateId,itemId
                };
                int rownumber = sqliteUtil.execute(Sql, args);
                if (rownumber == 0) {
                    throw new ServiceException("sqlite.message.addException");
                }
            }
        }
    }

    @Override
    public TemplateLinkItem findOne(String templateId, String itemId) {
        initConnection();
        String sql="select * from tab_config_link_template_item where TEMPLATE_ID = '"+templateId+"' and ELEMENT_ID = '"+itemId+"'";
        return sqliteUtil.selectOneRecord(TemplateLinkItem.class,sql);
    }

    @Override
    public List<TemplateLinkItem> findByItemId(String itemId) {
        initConnection();
        String sql = "select * from tab_config_link_template_item where  ELEMENT_ID = '" + itemId + "'";
        return sqliteUtil.selectListRecord(TemplateLinkItem.class, sql);
    }

    @Override
    public List<TemplateLinkItem> findAll(String templateId) {
        initConnection();
        String sql = "select * from tab_config_link_template_item where TEMPLATE_ID = '" + templateId + "'";
        return sqliteUtil.selectListRecord(TemplateLinkItem.class, sql);
    }

    @Override
    public void delete(String templateId, String elementId) {
        initConnection();
        String sql="delete from tab_config_link_template_item where TEMPLATE_ID = '" + templateId + "' and ELEMENT_ID = '" + elementId + "'";
        sqliteUtil.execute(sql);
    }
}
